#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>

#define COMMAND_SIZE 1024
#define FORMAT "(%s@%s %s)# "

#define MAXARGC 128
#define MAXENVS 128

char cwd[1024];
char cwdenv[1024];

//退出码
int exit_code = 0;

//命令行参数表
char* g_argv[MAXARGC];
int g_argc = 0;

//环境变量表
char* g_env[MAXENVS];
int g_envs = 0;

//获取当前用户名
const char* getUserName()
{
    const char* name = getenv("USER");
    return name == NULL ? "NONE" : name;
}

//获取当前主机名
const char* getHostName()
{
    const char* name = getenv("HOSTNAME");
    return name == NULL ? "NONE" : name;
}

//获取当前所在路径
const char* getPwd()
{
    //const char* pwd = getenv("PWD");
    const char* pwd = getcwd(cwd, sizeof cwd);
    if(pwd != NULL)
    {
        snprintf(cwdenv, sizeof cwdenv, "PWD=%s", cwd);
        putenv(cwdenv);
    }
    return pwd == NULL ? "NONE" : pwd;
}

//获取当前用户的家目录
const char* getHome()
{
    const char* home = getenv("HOME");
    return home;
}

//重定向类型定义
#define NONE_REDIR 0
#define INPUT_REDIR 1
#define OUTPUT_REDIR 2
#define APPEND_REDIR 3

int redir = NONE_REDIR;
std::string filename;

//模拟环境变量的获取
void InitEnv()
{
    extern char** environ;
    g_envs = 0;

    memset(g_env, 0, sizeof g_env);
    for(int i = 0; environ[i]; i++)
    {
        g_env[g_envs] = (char*)malloc(strlen(environ[i]) + 1);
        strcpy(g_env[g_envs], environ[i]);
        g_envs++;
    }
    //g_env[g_envs++] = (char*)"HAHA=haha";
    g_env[g_envs] = NULL;

    for(int i = 0; g_env[i]; i++)
    {
        putenv(g_env[i]);
    }
    environ = g_env;
}

//清理全局环境变量表
void CleanEnv()
{
    for(int i = 0; g_env[i]; i++)
    {
        free(g_env[i]);
        g_env[i] = NULL;
    }
    g_envs = 0;
}

void Cd()
{
    if(g_argc == 1)
    {
        std::string home = getHome();
        if(home.empty()) return;
        chdir(home.c_str());
    }
    else
    {
        std::string where = g_argv[1];
        if(where == "~")
        {

        }
        else if(where == "-")
        {

        }
        else
        {
            chdir(where.c_str());
        }
    } 
}

void Echo()
{
    int oldfd = -1;
    if(redir != NONE_REDIR)
    {
        oldfd = open(".tmp", O_CREAT | O_TRUNC | O_RDWR, 0666);
        if(oldfd < 0) exit(1);
    
        if(redir == INPUT_REDIR)
        {
            int fd = open(filename.c_str(), O_RDONLY);
            if(fd < 0) exit(1);
            dup2(0, oldfd);
            dup2(fd, 0);
        }
        else if(redir == OUTPUT_REDIR)
        {
            int fd = open(filename.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0666);
            if(fd < 0) exit(1);
            dup2(1, oldfd);
            dup2(fd, 1);
        }
        else if(redir == APPEND_REDIR)
        {
            int fd = open(filename.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0666);
            if(fd < 0) exit(1);
            dup2(1, oldfd);
            dup2(fd, 1);
        }
    }

    std::string op = g_argv[1];
    if(op == "$?")
    {
        printf("%d\n", exit_code);
        exit_code = 0;
    }
    else if(op[0] == '$')
    {
        std::string env_name = op.substr(1);
        const char* env_value = getenv(env_name.c_str());
        if(env_value)
        {
            printf("%s\n", env_value);
        }
    }
    else
    {
        std::cout << op << std::endl;
    }

    if(redir != NONE_REDIR)
    {
        if(redir == INPUT_REDIR) dup2(oldfd, 0);
        else if(redir == OUTPUT_REDIR || redir == APPEND_REDIR) dup2(oldfd, 1);
    }
}

//简化显示路径
std::string DirName(const char* pwd)
{
#define DELIM "/"
    std::string str = pwd;
    if(str == DELIM) return DELIM;
    size_t pos = str.rfind(DELIM);
    if(pos == std::string::npos) return "BUG";
    return str.substr(pos + 1);
}

//创建一个命令行提示符字符串
void makeCommandPrompt(char* prompt, int size)
{
    snprintf(prompt, size, FORMAT, getUserName(), getHostName(), DirName(getPwd()).c_str());
}

//打印命令行提示符
void PrintCommandPrompt()
{
    char prompt[COMMAND_SIZE];
    makeCommandPrompt(prompt, sizeof prompt);
    printf("%s", prompt);
    fflush(stdout);
}

//读入命令
bool GetCommandLine(char* out, int size)
{    
    char* c = fgets(out, size, stdin);
    if(c == NULL) return false;
    out[strlen(out) - 1] = 0; //清理\n
    if(strlen(out) == 0) return false;
    return true;
}

void TrimSpace(int& end, char* cmd)
{
    while(cmd[end] == ' ')
    {
        end++;
    }
}

//重定向检查
void CheckRedir(char* cmd)
{
    redir = NONE_REDIR;
    filename.clear();
    int begin = 0;
    int end = strlen(cmd) - 1;
    while(end > begin)
    {
        if(cmd[end] == '<') // 输入重定向
        {
            cmd[end++] = 0;
            TrimSpace(end, cmd);
            filename = cmd + end;
            redir = INPUT_REDIR;
            break;
        }
        else if(cmd[end] == '>')
        {
            if(cmd[end - 1] == '>') // 追加重定向
            {
                cmd[end - 1] = 0;
                cmd[end++] = 0;
                redir = APPEND_REDIR;
            }
            else // 输出重定向 
            {
                cmd[end++] = 0;
                redir = OUTPUT_REDIR;
            }
            TrimSpace(end, cmd);
            filename = cmd + end;
            break;
        }
        else 
        {
            end--;
        }
    }
}

//命令行解析
bool CommandParse(char* commandline)
{
#define SEP " "
    g_argc = 0;
    g_argv[g_argc++] = strtok(commandline, SEP);

    while((bool)(g_argv[g_argc] = strtok(nullptr, SEP)))
    {
        g_argc++;
    }
    return g_argc > 0 ? true : false;
}

//打印命令行参数表
void PrintArgv()
{
    for(int i = 0; g_argv[i]; i++)
    {
        printf("g_argv[%d]->%s\n", i, g_argv[i]);
    }
}

//检查并处理内建命令
bool CheckAndExecBuiltin()
{
    std::string str = g_argv[0];
    if(str == "cd")
    {
        Cd();
        return true;
    }
    else if(str == "echo")
    {
        Echo();
        return true;
    }
    return false;
}

//执行命令
int Execute()
{
    pid_t id = fork();
    if(id == 0)
    {
        int fd = -1;
        //重定向操作
        if(redir == INPUT_REDIR)
        {
            fd = open(filename.c_str(), O_RDONLY);
            if(fd < 0) exit(1);
            dup2(fd, 0);
        }
        else if(redir == OUTPUT_REDIR)
        {
            fd = open(filename.c_str(), O_CREAT | O_TRUNC | O_WRONLY, 0666);
            if(fd < 0) exit(1);
            dup2(fd, 1);
        }
        else if(redir == APPEND_REDIR)
        {
            fd = open(filename.c_str(), O_CREAT | O_APPEND | O_WRONLY, 0666);
            if(fd < 0) exit(1);
            dup2(fd, 1);
        }

        execvp(g_argv[0], g_argv);

        if(redir != NONE_REDIR) close(fd);
        exit(0);
    }
    
    int status = 0;
    pid_t rid = waitpid(id, &status, 0);
    if(rid > 0)//成功
    {
        exit_code = WEXITSTATUS(status);
    }
    return 0;
}

int main()
{
    InitEnv();

    while(true)
    {
        //1. 打印命令提示符
        PrintCommandPrompt();

        //2. 获取用户输入的命令
        char commandline[COMMAND_SIZE];
        if(!GetCommandLine(commandline, sizeof commandline))
        {
            continue;
        }
        //printf("echo %s\n", commandline);
        
        //3. 重定向检查
        CheckRedir(commandline);

        //4. 命令行解析
        if(!CommandParse(commandline))
            continue;

        //PrintArgv();
        //printf("%d\n", g_argc);
    
        //5. 检查并处理内建命令
        if(CheckAndExecBuiltin())
            continue;

        //6. 执行命令
        Execute();
    }

    CleanEnv();
    return 0;
}
